package com.cloud.common.support;

import com.cloud.common.context.AppContext;
import com.cloud.common.context.RequestContext;
import com.cloud.common.util.FormatUtils;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.core.env.Environment;

import java.io.IOException;

/**
 * 身份证脱敏序列化
 *
 * @author fengwenjin
 */
public class SensitiveIdCardSerializer extends JsonSerializer {
    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (RequestContext.isMaskData() && value != null && value instanceof String) {
            String valueStr = value.toString();
            if (valueStr.length() > 7) {
                String format = AppContext.getBean(Environment.class).getProperty("mask.format.idCard");
                gen.writeString(FormatUtils.maskFormat(valueStr, format));
                return;
            }
        }
        gen.writeObject(value);
    }
}
